<?php

namespace App\Api\V1\Controllers;

use Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

class LoginController extends Controller
{
    protected $guard = 'api';

    public function register(Request $request)
    {
        $rules = [
            'telephone' => [
                'required',
            ],
            'password' => 'required',
        ];

        $params = $this->validate($request,$rules);

        $telephone = $request->telephone;
        $username = $request->username;
        $password  = $request->password;

        $user = User::where('telephone',$telephone)->get();
        if ($user){
            return response()->json([
                'status' => '0',
                'msg' => '手机号已存在',
            ], 201);
        }

        $user = new User();

        $user->telephone = $telephone;
        $user->username = $username;
        $user->password  = $password;

        if (!$user->save()) {
            throw new HttpException(500);
        }
        $token = Auth::guard($this->guard)->login($user);

        return response()->json([
            'status' => 'ok',
            'token' => $token,
        ], 201);
    }

    public function login(Request $request)
    {
        $credentials = [
            'telephone' => $request->telephone,
            'password'  => $request->password
        ];

        try {

            $token = Auth::guard($this->guard)->attempt($credentials);

            if (!$token) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(compact('token'));
    }

    /**
     * 个人信息.
     *
     * @return User|null
     */
    public function userInfo(Request $request)
    {
        $rules = [
            'token' => 'required',
        ];

        $params = $this->validate($request,$rules);

        return Auth::guard('api')->user();
    }

    /**
     * 退出.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        $rules = [
            'token' => 'required',
        ];

        $params = $this->validate($request,$rules);
        Auth::guard($this->guard)->logout();

        return response()->json(['status' => 'ok']);
    }
}
